package com.quandou.base.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quandou.base.security.entity.QdUser;
import com.quandou.base.security.entity.SysUser;
import com.quandou.base.security.mapper.QdUserMapper;
import com.quandou.base.security.service.QdUserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class QdUserServiceImpl extends ServiceImpl<QdUserMapper, QdUser> implements QdUserService, UserDetailsService {
    private QdUserMapper qdUserMapper;
    private PasswordEncoder passwordEncoder;

    public QdUserServiceImpl(QdUserMapper qdUserMapper, PasswordEncoder passwordEncoder) {
        this.qdUserMapper = qdUserMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        QdUser qdUser = qdUserMapper.selectOne(new LambdaQueryWrapper<QdUser>().eq(QdUser::getUsername, username));

        if (null == qdUser) {
            throw new UsernameNotFoundException(username);
        }

        //TODO 查询角色以及权限
        List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
        SysUser sysUser = new SysUser(qdUser.getUsername(), qdUser.getPassword(), authorities);
        sysUser.setNickname(qdUser.getNickname());
        //TODO 其他待set的字段
        return sysUser;
    }
}
